import 'package:flutter/material.dart';
import 'package:netstorage/dao/search_dao.dart';
import 'package:netstorage/model/search_model.dart';
import 'package:netstorage/model/search_model_item.dart';
import 'package:netstorage/utils/navigator_utils.dart';
import 'package:netstorage/utils/view_utils.dart';
import 'package:netstorage/widget/search_bar_widget.dart';
import 'package:netstorage/widget/search_item_widget.dart';

class SearchPage extends StatefulWidget {
  final bool? hideLeft;// 隐藏左侧后退按钮
  final String? keyword;
  final String? hint;
  const SearchPage({super.key, this.keyword, this.hint, this.hideLeft = false});

  @override
  State<SearchPage> createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> {
  //#region state
  SearchModel? searchModel;
  String? keyword;
  //#endregion
  @override
  void initState() {
    super.initState();
    String kw = widget.keyword ?? '';
    if(kw.length > 0){
      _onTextChanged(kw);
    }
  }
  //#region build
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [ _appBar, _listView ],
      ),
    );
  }
  //#endregion
  //#region appBar
  get _appBar {
    double top = MediaQuery.of(context).padding.top;// 安全边距，从此处开始向下显示内容
    return shadowWrap(
        child: Container(
          height: 55 + top,// 本 appBar 自身高度55 + 安全边距
          child: SearchBarWidget(
            hideLeft: widget.hideLeft,
            defaultText: widget.keyword,
            hint: widget.hint,
            leftBtnClick: () => NavigatorUtils.pop(context),
            rightBtnClick: (){
              FocusScope.of(context).requestFocus(FocusNode());
            },
            onChanged: _onTextChanged,
          ),
        ),
        padding: EdgeInsets.only(top:top)// 从灵动岛下面开始显示
    );
  }
  //#endregion
  //#region listView
  get _listView => MediaQuery.removePadding(
      removeTop: true,
      context: context,
      child: Expanded(
          child: ListView.builder(
              itemCount: searchModel?.data?.length ?? 0,
              itemBuilder: (BuildContext context, int index){
                return _item(index);
              }
          ))
  );
  //#endregion
  //#region 文本框内容变动事件
  void _onTextChanged(String value) async {
    if(value == null || value.length == 0) return;
    try{
      SearchModel? data = await SearchDao.fetch();
      if(data == null) {
        print('请求搜索数据响应了空！');
        return;
      }

      // 不使用防抖的话要检测下面的 if 条件
      // 防止用户输入过快导致后端响应来的数据和用户输入的不一致
      // if(value == data.keyword){
      //   setState(() {
      //     searchModel = data;
      //   });
      // }

      setState(() {
        searchModel = data;
      });
    }catch(e){
      print('搜索内容时出现异常：${e.toString()}');
    }
  }
  //#endregion
  //#region 构建下拉列表的item
  _item(int index) {
    var item = searchModel?.data?[index];
    if(item == null || searchModel == null ) return Container(child: Text('没有数据'));
    return SearchItemWidget(searchModelItem: item, searchModel: searchModel);
  }
  //#endregion
}
